
import BetterSqlite3, { Database }  from 'better-sqlite3'
import { getResourcesDirPath } from '../utils/system'
import { fileURLToPath } from "node:url";
import path from 'node:path'

function initialize (db: Database){
    console.log(" init table --> app_para_config");
    db.exec(`
        CREATE TABLE IF NOT EXISTS app_para_config (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          name TEXT NOT NULL,
          email TEXT UNIQUE NOT NULL,
          created_at DATETIME DEFAULT CURRENT_TIMESTAMP
        )
    `)
}

function query(db: Database, sql: string, params: any[] = []){
    
    try {
        const stmt = db.prepare(sql)
        if (sql.trim().toUpperCase().startsWith('SELECT')) {
          return params.length > 0 ? stmt.all(params) : stmt.all()
        } else {
          return params.length > 0 ? stmt.run(params) : stmt.run()
        }
      } catch (error) {
        console.error('Database error:', error)
        throw error
      }
}
const APP_ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
const useSQLite3 = () => {
    const resource = getResourcesDirPath()
    console.log(path.join(resource, 'app.db'), "98989898");
    // const db = new BetterSqlite3(path.join(resource, 'app.db'))
    
    const db = new BetterSqlite3(path.join(resource, 'better-sqlite3.sqlite3'), {
      // https://github.com/WiseLibs/better-sqlite3/blob/v8.5.2/lib/database.js#L36
      // https://github.com/WiseLibs/better-sqlite3/blob/v8.5.2/lib/database.js#L50
      nativeBinding: path.join(APP_ROOT, import.meta.env.VITE_BETTER_SQLITE3_BINDING),
    })
    db.pragma('journal_mode = WAL')

    function find(sql: string, params: any[] = []){
        return query(db, sql, params)
    }
    initialize(db)
    return {
        db,
        find,
        info: 'success'
    }
}



export {
    useSQLite3,
    query,
}